package com.wuseguang.springcloud.dao.jdbc;

import com.wuseguang.springcloud.JdbcTemplate.BaseTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.PreparedStatement;
import java.sql.SQLException;

@Repository
public class QuestionnaireJdbc extends BaseTemplate {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public int insetAndUpdateQuestionnaireUsers(String listSql, String studentIds, Integer questionnaireType,Integer id) {
        try {
            logger.info("添加或者修改问卷用户,studentIds={},questionnaireType={}", studentIds, questionnaireType);
            String sql = " DELETE FROM questionnaire_users WHERE questionnaire_id=? ";
            updateByParameter(sql, id);
            String[] split = studentIds.split(",");
            return dao.batchUpdate(listSql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    String s = split[i];
                    ps.setInt(1, Integer.parseInt(s));
                    ps.setInt(2, questionnaireType);
                    ps.setInt(3, id);
                }

                @Override
                public int getBatchSize() {
                    return split.length;
                }
            }).length;
        } catch (Exception e) {
            logger.info("批量添加异常,error={}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
        }
        return 0;
    }
}
